package com.b2c.repository.tao;


import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.pdd.PddMarketingFeeEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.tao.TaoMarketingFeeEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Repository
public class TaoMarketingFeeRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static Logger log = LoggerFactory.getLogger(TaoMarketingFeeRepository.class);

    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }


    @Transactional
    public PagingResponse<TaoMarketingFeeEntity> getList(Integer pageIndex, Integer pageSize, Integer shopId, Integer type,String source, String startTime, String endTime) {
        List<Object> params = new ArrayList<>();
        StringBuilder sb = new StringBuilder("SELECT SQL_CALC_FOUND_ROWS o.*,sh.`name` as shopName,sh.`type` as shopType  ");
        sb.append(" FROM dc_tao_marketing_fee as o");
        sb.append(" left join dc_shop sh on sh.id=o.shopId ");

        sb.append(" WHERE 1=1 ");
        if(type!=null){
            sb.append(" AND o.type = ? ");
            params.add(type);
        }
        if(shopId!=null){
            sb.append(" AND o.shopId = ? ");
            params.add(shopId);
        }
        if (!StringUtils.isEmpty(startTime) ) {
            sb.append(" AND o.datetime >= ? ");
            params.add(startTime);
        }
        if (StringUtils.hasText(source) ) {
            sb.append(" AND o.source = ? ");
            params.add(source);
        }
        if (!StringUtils.isEmpty(endTime) ) {
            sb.append(" AND o.datetime <= ? ");
            params.add(endTime);
        }


        sb.append(" ORDER BY o.datetime DESC ");
        sb.append("  LIMIT ?,?");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        var list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(TaoMarketingFeeEntity.class), params.toArray(new Object[params.size()]));
        int totalSize = getTotalSize();
        return new PagingResponse<>(pageIndex, pageSize, totalSize, list);
    }

    @Transactional
    public ResultVo<String> importExcelFeeList(List<TaoMarketingFeeEntity> list, Integer shopId,String source) {
        if (list == null || list.size() == 0)
            return new ResultVo<>(EnumResultVo.DataError, "参数错误：缺少list", "");

        /******* 插入数据 ********/
        int totalInsert = 0;// 新增数量
        int totalExist = 0;// 已存在数量
        int totalError = 0;// 错误数量
        for (var item : list) {
            try {
                // 查询数据是否存在
                var oList = jdbcTemplate.query(
                        "SELECT * FROM dc_tao_marketing_fee WHERE type=? AND amount=? AND shopId=? AND `datetime`=?",
                        new BeanPropertyRowMapper<>(PddMarketingFeeEntity.class), item.getType(),
                        item.getAmount(), shopId, item.getDatetime());
                if(oList !=null && oList.size()>0){
                    log.error("Fee新增错误,已存在：" + JSONObject.toJSONString(item));
                    totalExist++;
                }else {
                    // 不存在添加，存在不添加

                    /************** 1、新增fee **********************/
                    StringBuilder insertSQL = new StringBuilder();
                    insertSQL.append("INSERT INTO dc_tao_marketing_fee ");
                    insertSQL.append(" (datetime,`date`,shopId,amount,type,transactionType,balance,remark,source) ");
                    insertSQL.append(" VALUE (?,?,?,?,?,?,?,?,?) ");

                    jdbcTemplate.update(insertSQL.toString(), item.getDatetime(),item.getDate(), shopId,
                            item.getAmount(), item.getType(), item.getTransactionType(),item.getBalance(), item.getRemark(),item.getSource());

                    totalInsert++;// 新增成功

                }
            } catch (Exception e) {
                totalError++;
                log.error("Fee新增错误,系统异常：" + e.getMessage() + item.getDatetime());

                return new ResultVo<>(EnumResultVo.SystemException, "系统异常：" + e.getMessage(), "");
            }
        }

        String msg = "Fee新增成功：" + totalInsert + "，失败：" + totalError + "，已存在：" + totalExist;
        //// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS", msg);

    }
}
